/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

var pr_ajax = null;
var form = null;
window.addEvent('load', function(){
	if(typeof(document.adminForm)!=='undefined'){
		form = document.adminForm;
	}
});

if( typeof(makeSelectSave) == 'undefined' ){
	var makeSelectSave = 'Please make a selection from the list to save';
	var makeSelectView = 'Please make a selection from the list to view detail';
	var makeSelectDelete = 'Please make a selection from the list to delete';
}

function submitbutton_multi_view(pressbutton, max, formName){
	if ( !check_list(max, formName) ) {
		if (pressbutton=='multi_starred')
			alert(makeSelectSave);
		if (pressbutton=='multi_view')
			alert(makeSelectView);
		if (pressbutton=='multi_delete')
			alert(makeSelectDelete);
		return;
	}
	
    eval("document."+formName+".task.value = pressbutton;");
    eval("document."+formName+".submit()");
} 

function submitbutton_multiview_jobs(pressbutton, max, formObjCall){
	var form_emp = formObjCall;
	if (pressbutton!='job_list_via_profiles')
		form_emp.view.value = 'japrofiles';
	else{		
		form_emp.view.value = 'jajobs';
		form_emp.action = 'index.php?option=com_jajobboard&view=jajobs&layout=jalist';
	}
	form_emp.method = 'get';
	form_emp.task.value = pressbutton;
	form_emp.submit();
}

function submitbutton(pressbutton) {
    if(pressbutton == 'apply' || pressbutton == 'save'){
        // check require
    }
    form.task.value = pressbutton;
    form.submit();
}

function submitbuttonGeneral(pressbutton) {
    if(pressbutton == 'apply' || pressbutton == 'save'){
        // check require
    }
    form.task.value = pressbutton;
    form.submit();
}

function tableOrdering( order, dir, task ) {    
    var url = location.href;
    pos = url.indexOf('#');
	if(pos > 0) {
		queryStr = url.substr(pos);
	}else {
		queryStr = '';
	}
	
	form.filter_order.value     = order;
    form.filter_order_Dir.value    = dir;
    form.task.value = task;
    form.action = form.action + queryStr;
 
    form.submit();
}

function listItemTask( id, field, task ) {
    var f = document.adminForm;
        
        f.cids.value = id;
        f.boxcheck.value = 1;
        f.task.value = task;
        f.field.value = field;
        
     	if(field == 'is_starred')
     	{
            var strTask = "starred";
            
	        if(task == 'activate')
	        	strTask = "starred";
	        else
	        	strTask = "unstarred";
            
	        try{
		        var url ='index.php?option=com_jajobboard&view=jashortlist&table_name=' + table_name +'&tmpl=component&task=' + strTask + '&cid[]=' + id + '&Itemid=' + Itemid;
				
		        var req = new Ajax(url, {
					method: 'get',
					update: $('log')
				});
				
				req.request();			
				
				var iconActive = '';
				var strOnclick = '';
				var title = "Remove Favorite";
				if(task == 'activate')
				{
					iconActive = siteurl + '/components/com_jajobboard/images/Favorites-16x16.png';					
					strOnclick =  "listItemTask('" + id + "','is_starred','inactivate')";
					
				}else
				{
					iconActive = siteurl + '/components/com_jajobboard/images/favorite-remove-16x16.png';
					var title = "Set as Favorite";
					strOnclick =  "listItemTask('" + id + "','is_starred','activate')";
				}			
				$('img_' + id).src = iconActive;
				$('img_' + id).title = title;
				$('hrf_' + id).onclick = new Function(strOnclick);
				
	        }catch(err)
	        {
	        	alert(err);
	        }
     	}
     	else
     	{
     		 f.submit();
     	}                  
}

function show_edit_note(item_id)
{
	edit_div = $('edit_note_'+item_id);
	edit_div.setStyle('display','block');
	view_div = $('view_note_'+item_id);
	view_div.setStyle('display','none');
	edit_button_div = $('div_edit_button_'+item_id);
	edit_button_div.setStyle('display','block');
	view_button_div = $('div_view_button_'+item_id);
	view_button_div.setStyle('display','none');
	$('description_'+item_id).value = saved_note_value;
}

function save_note(item_id, user_id, note_type)
{
	saved_note = true;
	if( $('description_'+item_id).value == ""){
		alert("Please input note message!");
		return;
	}
	saved_note_value = $('description_'+item_id).value;
	if( save_note_url.indexOf('?') < 0)
		var url = save_note_url+'?task=ajax_save&user_id=' + user_id + '&note_type='+note_type+'&item_id='+item_id+'&&description=' + $('description_'+item_id).value;
	else
		var url = save_note_url+'&task=ajax_save&user_id=' + user_id + '&note_type='+note_type+'&item_id='+item_id+'&&description=' + $('description_'+item_id).value;
	new Ajax(url, {method:'get', onComplete:update_saved_note}).request();	
}

function update_saved_note(text){
	
	item_id = text.substring(0,text.indexOf('_'));
	item_id = parseInt(item_id);
		
	var description = text.substring(text.indexOf('_')+1, text.length);

	var edit_div = document.getElementById('edit_note_'+item_id);
		
	view_description_note = document.getElementById('view_description_' + item_id);

	view_description_note.innerHTML = description;

	edit_div.style.display = 'none';

	var view_div = document.getElementById('view_note_'+item_id);

	view_div.style.display = 'block';

	var edit_button_div = document.getElementById('div_edit_button_'+item_id);

	edit_button_div.style.display = 'none';

	var view_button_div = document.getElementById('div_view_button_'+item_id);

	view_button_div.style.display = 'block';

	var div_addnote_button = document.getElementById('div_addnote_button_' + item_id);
	
	if (div_addnote_button){
		div_addnote_button.style.display = 'none';
	}
    

}

function cancel_note(item_id){
	if( !saved_note ){
		$('add_note_' + item_id).setStyle( 'display', 'block');
		if(document.getElementById('description_' + item_id).value == "" || saved_note_value == "" )
			$('add_note_' + item_id).setStyle( 'display', 'none');
	}else{
		var edit_div = document.getElementById('edit_note_'+item_id);
		edit_div.style.display = 'none';
		var view_div = document.getElementById('view_note_'+item_id);
		view_div.style.display = 'block';
		var edit_button_div = document.getElementById('div_edit_button_'+item_id);
		edit_button_div.style.display = 'none';
		var view_button_div = document.getElementById('div_view_button_'+item_id);
		view_button_div.style.display = 'block';
	}
}

function check_list(max, formName){
	if( typeof(formName) == "undefined" )
		formName = "adminForm";
	for (i=0;i<max;i++){	
		cb_obj = document.getElementById('cb'+i+formName);
		if (cb_obj.checked)
			return true;
	}
	return false;
}    


function jalist_show_box_action(obj, formName){
	if(typeof(formName) == "undefined")
		formName = "adminForm";
	
	if(obj.checked){
		boxfx = new Fx.Style($('ja-box-action'), 'bottom', {duration:300});
		boxfx.stop();
		boxfx.start(0);
		
	}
	else if($('boxchecked'+formName).value==0){
		if ( typeof(boxfx) == "undefined" ){
			boxfx = new Fx.Style($('ja-box-action'), 'bottom', {duration:300});
		}
		boxfx.stop();
		boxfx.start(-60);
	}
	if (obj.name!='toggle')
		$('count-selection').innerHTML = $('boxchecked'+formName).value;
	else
	{
		if (obj.checked)
		{
			if (parseInt($('limit').value)>parseInt($('total_item').value))
			{
				var number_selected_item = $('total_item').value;
				
			}
			else
			{
				var number_selected_item = $('limit').value;
				
			}
			$('count-selection').innerHTML = number_selected_item;
			$('boxchecked'+formName).value = number_selected_item;
			if (!boxfx){
				boxfx = new Fx.Style($('ja-box-action'), 'bottom', {duration:300});
			}
			boxfx.stop();
			boxfx.start(0);
		}
		else
		{
			$('count-selection').innerHTML = 0;
			$('boxchecked'+formName).value = 0;
			if (!boxfx){
				boxfx = new Fx.Style($('ja-box-action'), 'bottom', {duration:300});
			}
			boxfx.stop();
			boxfx.start(-60);
		}
	}
	
}

function updateselectedjobs(formName, obj){
	if (!obj.checked){
		$('li_'+obj.value).removeClass('selected');
	}
	else{
		$('li_'+obj.value).addClass('selected');
	}
	
	$('selectedJobs'+formName).value = $('boxchecked'+formName).value + ' ' + select_text;
	$('selectedJobs2'+formName).value = $('boxchecked'+formName).value + ' ' + select_text;
}

function updateselectedResume(formName, cbObj){
	if( typeof(cbObj) == "undefined" )
		return;
	var checked = cbObj.checked;
	if (!checked){
		$('li_'+cbObj.value).removeClass('selected');
	}
	else{
		$('li_'+cbObj.value).addClass('selected');
	}
	
	$('selectedJobs'+formName).value = $('boxchecked'+formName).value + ' ' + select_text_resume;
	$('selectedJobs2'+formName).value = $('boxchecked'+formName).value + ' ' + select_text_resume;
}

function updateselectallResumes(formName, obj,num_obj){
	
	for (i=0;i<num_obj;i++)
	{
		updateselectedResume(formName, $('cb'+i+formName) );
	}
	$('selectedJobs'+formName).value = $('boxchecked'+formName).value + ' ' + select_text_resume;
	$('selectedJobs2'+formName).value = $('boxchecked'+formName).value + ' ' + select_text_resume;
}

function updateselectalljobs(formName, obj,num_obj){
	
	for (i=0;i<num_obj;i++)
	{
		updateselectedjobs(formName, $('cb'+i+formName));
	}
	
	$('selectedJobs'+formName).value = $('boxchecked'+formName).value + ' ' + select_text;
	$('selectedJobs2'+formName).value = $('boxchecked'+formName).value + ' ' + select_text;
}

function submit_searchform(pressbutton)
{
	form = document.adminForm;
	if (pressbutton == 'search')
		form.submit();
	else
	{
		form.filter_title.value='';
		form.filter_created_date.value='';
		form.filter_education.value='';
		form.filter_location_id.value='';
		form.submit();
	}
}

function child_selection(obj,obj_option)
{
	var inc_array = new Array(obj_option.value);
	
if (obj_option.selected)	
	for (i=0;i<obj.options.length;i++)
	if (in_array(obj.options[i].value,inc_array))
	{
		if (obj.options[i].selected)
		{
			if (obj.id=='location_id')
			{
				if (child_location_id[obj.options[i].value])	
					for (k=0;k<child_location_id[obj.options[i].value].length;k++)
						for (ii=i+1;ii<obj.options.length;ii++)
							if (obj.options[ii].value==child_location_id[obj.options[i].value][k])
							{
								obj.options[ii].selected = true;
								inc_array[inc_array.length] = obj.options[ii].value;
							}
			}
			else
			{
				if (child_cat_id[obj.options[i].value])	
					for (k=0;k<child_cat_id[obj.options[i].value].length;k++)
						for (ii=i+1;ii<obj.options.length;ii++)
							if (obj.options[ii].value==child_cat_id[obj.options[i].value][k])
							{
								obj.options[ii].selected = true;
								inc_array[inc_array.length] = obj.options[ii].value;
							}
			}
		}
	}

}
function in_array(ele, inc_array)
{
	for (x in inc_array)
		if (inc_array[x]==ele)
			return true;
	return false;	
}
function cal_number_selection(field_name,child_array)
{
	sum_selection = 0;
	obj = document.getElementById(field_name);
	if (obj)
	for (i=0;i<obj.options.length;i++)
	{
		if (!check_exist_child(child_array,obj.options[i].value)&&obj.options[i].selected)
			sum_selection++;
	}
	return sum_selection;
	
}
function check_exist_child (child_array,ele)
{
	if (child_array[ele])
		return true;
	else
		return false;
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function  moveContent(objID){
	eleID = objID.indexOf('-');
	eleID = objID.substring(0,eleID);
	var content =  tinyMCE.activeEditor.getContent({format : 'raw'});
	$(eleID).value = content;
	
}

function checkAlls( formName, n, fldName ) {
	if (!fldName) {
	 fldName = 'cb';
	}
	
	var f = formName;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i + f.name);		
		if (cb) {			
			cb.checked = c;
			n2++;			
		}
	}
	
	if (c) {		
		formName.boxchecked.value = n2;
	} else {
		formName.boxchecked.value = 0;
	}
}

function ajaxOrder(filter_order, filter_order_dir){
	var url = location.href;
	
}

function ajaxPagination(url,divid) {	
	displayLoadingSpan();
	if(pr_ajax != null){
		pr_ajax.cancel();
	}
	pr_ajax = new Ajax(url,{method:'get', update:divid, onComplete:update}).request();
	
}

function update(request) {
	if ($('ja-loader'))
		$('ja-loader').setStyle ('display', 'none');
	
	var JTooltips = new Tips($$('#jobboard-content .hasTip'), { maxTitleChars: 50, fixed: false});
	if(typeof(document.adminForm)!=='undefined'){
		form = document.adminForm;
	}
}

function displayLoadingSpan() {
	if(!$type($('ja-loader'))){
		var loader = new Element('div', {'id': 'ja-loader'});
		loader.setText('Loading...');
		if($type($('jobboard-content'))){
			loader.injectBefore($('jobboard-content'));
		}
		else{
			loader.injectInside(document.body);
		}
					
	}
	if($type($('ja-loader'))){
		$('ja-loader').setStyle('display', 'block');
	}
}
//Build data by search params from filters
function buildData(){		
	// Build data for categories
	var full_of_checked;
	var temp_data;	
	var temp_frm;
	var temp_list;
	var filter_data = '';
	var arr_cat_data = new Array();
	var label_active = new Array();
		
	//******************** UPDATE LOCATION, CATEGORY FILTER ********************
	if( typeof(filter) != "undefined" )
	for ( var j=0;j<filter.length;j++)
	{
		label_active[j] = '';
		temp_data = '';
		temp_frm = document.forms['form_'+filter[j]];
		
		if (temp_frm != null){
			temp_list = document.getElementsByName('filter_'+filter[j]+'[]');//category_frm['filter_'+filter[j]+'[]'];
			
			full_of_checked = true;
			var temp_count = 0;
			for(var i=0; i<temp_list.length; i++){
				if (temp_list[i].checked)
				{
					if (temp_data=='')
					{
						temp_data +=  get_name_from_value(temp_list[i].value);
						
					}
					else
					{
						temp_data += ',' + get_name_from_value(temp_list[i].value);
						
					}
					
					label_active[j] += ' <span style="width:auto;" id="'+filter[j]+'_active_'+temp_count+'">' + temp_list[i].title + '<span onclick="delete_active('+get_id_from_value(temp_list[i].value)+',\''+filter[j]+'\',\''+filter[j]+'_active_'+temp_count+'\');"> <img src="' + siteurl + 'modules/mod_jafilter_jobs/ja_filter_jobs/images/del.gif" alt="Delete" /></span></span>';
			//Get label
					arr_cat_data[temp_count] = temp_list[i];	
										
					temp_count++;
				}		
				else{
					full_of_checked = false;
				}
			}
			// alert(filter[j])
			 $('filter-active-'+filter[j]).setHTML(label_active[j]);
			if(label_active[j].trim()==''){
				$('filter-active-'+filter[j]).setStyle('display','none');
				$('filter-inactive-'+filter[j]).setStyle('display','block');
			}
			else{
				$('filter-inactive-'+filter[j]).setStyle('display','none');
				$('filter-active-'+filter[j]).setStyle('display','block');
			}
			
			if (full_of_checked ) temp_data = '';
			
		}
		if(temp_data!=''){
			filter_data += '&'+filter[j]+ "=" + temp_data;
		}
	}

	
	//******************** END ********************
	//******************** UPDATE KEYWORD FILTER ********************
	if ($type($('filter_keyword')) && $type($('default_keyword')) && $('filter_keyword').value!=$('default_keyword').value)
	{
		filter_data += '&filter_keyword='+$('filter_keyword').value;
//		label_active_keyword = ' <span style="width:auto;" id="keyword_active_label">' + $('filter_keyword').value + '<span onclick="delete_text_active(\'filter_keyword\',\''+'keyword_active_label'+'\');"> <img src="' + siteurl + 'modules/mod_jafilter_jobs/ja_filter_jobs/images/del.gif" alt="Delete" /></span></span>';
//		$('filter-inactive-keyword').style.display = 'none';
//		$('filter-active-keyword').style.display = 'block';
//		$('filter-active-keyword').innerHTML = label_active_keyword;
	}
	else
	{
//		$('filter-active-keyword').innerHTML = '&nbsp;';
//		$('filter-active-keyword').style.display = 'none';
//		$('filter-inactive-keyword').style.display = 'block';
	}
	//******************** END ********************
	
	//******************** UPDATE SALARY FILTER ********************
	if($type($('filter_salary_from'))){
		label_active_salary = '';
		if ($('filter_salary_from').value!='')
		{
			filter_data += '&filter_salary_from=' + $('filter_salary_from').value;
			label_active_salary = ' <span style="width:auto;" id="salary_from_active_label">' + $('filter_salary_from').value + '<span onclick="delete_text_active(\'filter_salary_from\',\''+'salary_from_active_label'+'\');"> <img src="' + siteurl + 'modules/mod_jafilter_jobs/ja_filter_jobs/images/del.gif" alt="Delete" /></span></span>';
		}
		if ($('filter_salary_to').value!='')
		{
			filter_data += '&filter_salary_to=' + $('filter_salary_to').value;
			label_active_salary += ' <span style="width:auto;" id="salary_to_active_label">' + $('filter_salary_to').value + '<span onclick="delete_text_active(\'filter_salary_to\',\''+'salary_to_active_label'+'\');"> <img src="' + siteurl + 'modules/mod_jafilter_jobs/ja_filter_jobs/images/del.gif" alt="Delete" /></span></span>';
		}
		if (label_active_salary!='')
		{
			if( $('filter-inactive-salary') && $('filter-active-salary') ){
				$('filter-inactive-salary').setStyle('display','none');
				$('filter-active-salary').setStyle('display','block');
				$('filter-active-salary').setHTML(label_active_salary);
			}
		}
		else
		{
			if( $('filter-inactive-salary') && $('filter-active-salary') ){
				$('filter-inactive-salary').setStyle('display','block');
				$('filter-active-salary').setStyle('display','none');
				$('filter-active-salary').setHTML('');
			}
		}
	}
	//******************** END ********************
	return filter_data;
}

function doSearch(layout){
	if ($type($('filter_keyword')) && $type($('default_keyword')) && $('filter_keyword').value!=$('default_keyword').value)
	{
		if($('filter_keyword').value.trim()!='' && $('filter_keyword').value.length<3){
			alert('Minimum length of keyword must be at least 3 characters');
			$('filter_keyword').focus();
			return;
		}
	}
	
	var url = location.href;
	// Display loading icon	
	displayLoadingSpan();
	
	// Use AJAX to do search and reload listing area
	var filter_data = buildData();
	
	if($type($('limit'))){
		filter_data += '&limit='+$('limit').value;
	}	
	
	if((typeof layout)=='undefined'){
		layout = 'filter_job_list';
	}
	
	var mainUrl = siteurl+"index.php?tmpl=component&option=com_jajobboard&view=jajobs&ajax=1&dosearch=1&Itemid=" + itemid + '&layout=' + layout;
	if($('filter_order')!=null){
		mainUrl += "&filter_order=" + escape($('filter_order').value) + '&filter_order_Dir=' + $('filter_order_Dir').value;
	}
	
	var urlrequest = mainUrl + filter_data;
	
	pos = url.indexOf('#');
	if(pos > 0) {
		queryStr = url.substr(pos);
	}else {
		queryStr = '';
	}

	url = url.replace(queryStr, '');
	
	var newUrl = url + '#Top'+ filter_data;
//	newUrl = ad_replace("option=","&",newUrl,"option=com_jajobboard&");
//		newUrl = ad_replace("&view","&",newUrl,"&view=jajobs&");
//		newUrl = ad_replace("&layout","&",newUrl,"&layout=jalist&");
	if($('filter_order')!=null){
		newUrl += "&filter_order=" + escape($('filter_order').value) + '&filter_order_Dir=' + $('filter_order_Dir').value;
	}
	
	
	if ($type($('jobboard-content'))){
		window.location = newUrl;
		new Ajax(urlrequest, {'method':'get', 'update': 'jobboard-content', 'onComplete': update}).request();
	}
	else{
		if(redirect_url.indexOf('?') <0) {
			redirect_url = redirect_url + '?';
		}
		window.location = redirect_url + filter_data;
	}
	
}

// Checked job identifier
function isCheckedJob(Form, checked){
	if( typeof(Form) == "undefined" ){
		Form = document.adminForm;
	}
	
	if( typeof(Form.boxchecked) == "undefined" ){
		return ;
	}
	
	if (checked == true){
		Form.boxchecked.value++;
	} else {
		Form.boxchecked.value--;
	} 
	
}